package com.network.retrofit.utils;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.telephony.CellInfo;
import android.telephony.CellInfoGsm;
import android.telephony.CellInfoLte;
import android.telephony.CellInfoWcdma;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;



import java.util.List;

/**
 * 项目创建人:
 * 创建人:fargo(罗)
 * Created by app on 2020/10/14  —————— 16:17
 * 作用:
 * 备注:
 **/
public class NetWorkPowerLevelUtils {

    private Context context;
    private TelephonyManager telephonyManager;
    private String str;
    private int mLevel=0;
    private NetWorkState netWorkState;

    public NetWorkPowerLevelUtils(Context context) {
        this.context = context;
    }

    public interface NetWorkState{
        void stateResult(boolean isBad,int level);
    }

    public void setNetWorkState(NetWorkState netWorkState) {
        this.netWorkState = netWorkState;
    }

    /**
     * 设置并通知好坏
     * @param isBad 网络状况是否良好
     */
    private void sendState(boolean isBad) {
        if(netWorkState!=null){
            netWorkState.stateResult(isBad,mLevel);
        }
    }


    /**
     * 启动监听
     */
    public void monitorLever() {
        try {
            if (context == null) {
                return;
            }
            if (telephonyManager == null) {
                telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                //监听信号强度
                telephonyManager.listen(MyPhoneListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 手机状态监听
     */
    PhoneStateListener MyPhoneListener = new PhoneStateListener() {
        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            super.onSignalStrengthsChanged(signalStrength);
            NetWorkLogUtil.logE("signalStrength","signalStrength");

            //没有网络-0：WIFI网络1：4G网络-4：3G网络-3：2G网络-2
            switch (getApnType(context)) {
                case 0:
                    str = "网络已断开,没有网络";
                    NetWorkLogUtil.logE(str);
                    sendState(true);
                    break;
                case 1:
                    str = "当前网络为wifi";
                    NetWorkLogUtil.logE(str);
                    if (checkWifiState() == 1 || checkWifiState() == 0) {
                        sendState(false);
                    } else {
                        sendState(true);
                    }
                    break;
                case 2:
                    str = "当前网络为2G移动网络";
                case 3:
                    str = "当前网络为3G移动网络";
                case 4:
                    str = "当前网络为4G移动网络";
                    NetWorkLogUtil.logE(str);

                    //Todo 如果SDK 大于6.0 可以用直接提供的 方法判断强弱
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        //Todo 获取0-4移动、电信或0~5为联通的信号级别   越大信号越好
                        NetWorkLogUtil.logE("getLevel", signalStrength.getLevel());
                        int level = signalStrength.getLevel();
                        mLevel=level;
                        if (level >= 3) {
                            sendState(false);
                        } else {
                            sendState(true);
                        }
                    } else {
                        //有一种反射的方式获取  这里不使用它  因为反射消耗性能并且 随着SDK的变化 方法可能变化 可能获取不到正确的值
                     /*   Method method = signalStrength.getClass().getMethod("getDbm");
                        int mGsmSignalStrength = (int) method.invoke(signalStrength);
                        NetWorkLogUtil.LOGE("mGsmSignalStrength", mGsmSignalStrength);
                        if (mGsmSignalStrength > -90) {
                            Log.e("tiwolf", "getNetWorkInfo: 信号强度强");
                        } else {
                            Log.e("tiwolf", "getNetWorkInfo: 信号强度弱");
                        }*/
                        int level = 0;
                        int dbm = 0;
                        int asu = 0;
                        //Todo 不推荐使用反射，有精力可以去搞一下
                        //此处需要申请这个权限获取信息
                        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            return;
                        }
                        List<CellInfo> infos = telephonyManager.getAllCellInfo();
                        if (infos == null) {
                            return;
                        }
                        for (CellInfo info : infos) {
                            if (!info.isRegistered()) {
                                continue;
                            }
                            if (info instanceof CellInfoLte) {//4G
                                CellInfoLte ff = (CellInfoLte) info;
                                dbm = ff.getCellSignalStrength().getDbm();
                                level = ff.getCellSignalStrength().getLevel();
                                asu = 140 + dbm;
                            } else if (info instanceof CellInfoWcdma) {//3G
                                CellInfoWcdma ff = (CellInfoWcdma) info;
                                dbm = ff.getCellSignalStrength().getDbm();
                                level = ff.getCellSignalStrength().getLevel();
                                asu = (dbm + 113) / 2;
                            } else if (info instanceof CellInfoGsm) {//2G
                                CellInfoGsm ff = (CellInfoGsm) info;
                                dbm = ff.getCellSignalStrength().getDbm();
                                level = ff.getCellSignalStrength().getLevel();
                                asu = (dbm + 113) / 2;
                            }
                            NetWorkLogUtil.logE("Level:" + level);
                            mLevel=level;
                            if (level >= 3) {
                                sendState(false);
                            } else {
                                sendState(true);
                            }
                        }
                    }
                    break;
            }

        }
    };


    /**
     * 获取当前的网络状态 ：没有网络-0：WIFI网络1：4G网络-4：3G网络-3：2G网络-2
     * 自定义
     *
     * @param context
     * @return
     */
    public static int getApnType(Context context) {
        //结果返回值
        int netType = 0;
        //获取手机所有连接管理对象
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context
                .CONNECTIVITY_SERVICE);
        //获取NetworkInfo对象
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        //NetworkInfo对象为空 则代表没有网络
        if (networkInfo == null) {
            return netType;
        }
        //否则 NetworkInfo对象不为空 则获取该networkInfo的类型
        int nType = networkInfo.getType();
        if (nType == ConnectivityManager.TYPE_WIFI) {
            //WIFI
            netType = 1;
        } else if (nType == ConnectivityManager.TYPE_MOBILE) {
            int nSubType = networkInfo.getSubtype();
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService
                    (Context.TELEPHONY_SERVICE);
            //3G   联通的3G为UMTS或HSDPA 电信的3G为EVDO
            if (nSubType == TelephonyManager.NETWORK_TYPE_LTE
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 4;
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_UMTS
                    || nSubType == TelephonyManager.NETWORK_TYPE_HSDPA
                    || nSubType == TelephonyManager.NETWORK_TYPE_EVDO_0
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 3;
                //2G 移动和联通的2G为GPRS或EGDE，电信的2G为CDMA
            } else if (nSubType == TelephonyManager.NETWORK_TYPE_GPRS
                    || nSubType == TelephonyManager.NETWORK_TYPE_EDGE
                    || nSubType == TelephonyManager.NETWORK_TYPE_CDMA
                    && !telephonyManager.isNetworkRoaming()) {
                netType = 2;
            } else {
                netType = 2;
            }
        }
        return netType;
    }


    /**
     * wifi 是否连接
     *
     * @return
     */
    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        //android 6.0之后把NetworkInfo 标记过时了，它的方法基本都标记过时了
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (connManager != null) {
                Network networks = connManager.getActiveNetwork();
                NetworkCapabilities networkCapabilities = connManager.getNetworkCapabilities(networks);
                if (networkCapabilities != null) {
                    if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        Log.e("-----------wifi", "wifi");
                        return true;
                    } else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        Log.e("-----------流量", "手机流量");
                    }
                } else {
                    Log.e("------------没有网络", "没有网络");
                }
            }
        }else{
            NetworkInfo activeNetInfo = connManager.getActiveNetworkInfo();
            if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                return true;
            }
        }
        return false;
    }




    /**
     * 监测wifi 强度 -1无连接  0最强  1较强 2较弱 3弱  4网络监测出错
     *
     * @return
     */
    public int checkWifiState() {
        if (isWifiConnect()) {
            WifiManager mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo mWifiInfo = mWifiManager.getConnectionInfo();
            //获取wifi信号强度
            int wifi = mWifiInfo.getRssi();
            //最强
            if (wifi > -50 && wifi < 0) {
                Log.e("wifi强度", "最强");
                mLevel=4;
                return 0;
            }
            //较强
            else if (wifi > -70 && wifi < -50) {
                Log.e("wifi强度", "较强");
                mLevel=3;
                return 1;
            }
            //较弱
            else if (wifi > -80 && wifi < -70) {
                Log.e("wifi强度", "较弱");
                mLevel=2;
                return 2;
            }
            //微弱
            else if (wifi > -100 && wifi < -80) {
                Log.e("wifi强度", "微弱");
                mLevel=1;
                return 3;
            } else {
                mLevel=0;
                return 4;
            }
        } else {
            //无连接
            Log.e("wifi强度", "无wifi连接");
            return -1;
        }
    }

}
